<template>
  <div class="app-container">
    <!-- Header 头部区域 -->
    <MyHeader header-title="购物车"></MyHeader>
    <!-- <h1>App 根组件</h1> -->
    <MyGoods
      v-for="item in goodsLists"
      :key="item.id"
      :title="item.goods_name"
      :id="item.id"
      :goods-price="item.goods_price"
      :state="item.goods_state"
      :image="item.goods_img"
      :count="item.goods_count"
      @state-change="getNewState"
    >
      <Counter
        :num="item.goods_count"
        @num-change="getNewNum(item, $event)"
      ></Counter>
    </MyGoods>
    <!-- Footer 底部区域 -->
    <MyFooter
      :is-all-selected="isAllSelected"
      :amount="amt"
      :total-count="totalCount"
      @full-selected-change="changeAllState"
    ></MyFooter>
  </div>
</template>

<script>
// 导入子组件
import MyHeader from "@/components/Header/Header.vue";
import MyGoods from "@/components/Goods/Goods.vue";
import MyFooter from "@/components/Footer/Footer.vue";
import Counter from "@/components/Counter/Counter.vue";

export default {
  components: {
    MyHeader,
    MyGoods,
    MyFooter,
    Counter,
  },
  data() {
    return {
      goodsLists: [],
    };
  },
  methods: {
    //  请求列表数据
    async initCartList() {
      const { data: res } = await this.$http.get("/api/cart");
      // console.log(res);
      if (res.status === 200) {
        this.goodsLists = res.list;
      }
    },
    // 获取 goods 勾选状态
    getNewState(val) {
      // console.log("App Component", val);
      this.goodsLists.some((item) => {
        if (item.id === val.id) {
          item.goods_state = val.state;
          return true;
        }
      });
    },
    // goods 全选状态的变化
    changeAllState(val) {
      // console.log("App Component", val);
      this.goodsLists.forEach((item) => {
        item.goods_state = val;
      });
    },
    // 更改商品数量
    getNewNum(item, e) {
      // console.log(item, e);
      item.goods_count = e;
    },
  },
  // 计算属性
  computed: {
    // 全选功能
    isAllSelected() {
      return this.goodsLists.every((item) => item.goods_state);
    },
    // 勾选商品总价
    amt() {
      return this.goodsLists
        .filter((item) => item.goods_state)
        .reduce(
          (amount, item) => (amount += item.goods_price * item.goods_count),
          0
        );
    },
    totalCount() {
      return this.goodsLists
        .filter((item) => item.goods_state)
        .reduce((total, item) => (total += item.goods_count), 0);
    },
  },
  // 周期函数
  created() {
    // console.log(this);
    this.initCartList();
  },
};
</script>

<style lang="less" scoped>
.app-container {
  padding-top: 45px;
  padding-bottom: 50px;
}
</style>
